{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. 异常处理"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.1 错误与异常\n",
    "\n",
    "- 语法错误\n",
    "- 异常"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.2 处理异常\n",
    "\n",
    "```python\n",
    "try:\n",
    "    s = input('please enter two numbers separated by comma: ')\n",
    "    num1 = int(s.split(',')[0].strip())\n",
    "    num2 = int(s.split(',')[1].strip())\n",
    "except ValueError as err:\n",
    "    print('Value Error: {}'.format(err))\n",
    "\n",
    "print('continue')\n",
    "``"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.3 自定义异常\n",
    "\n",
    "```python\n",
    "class MyInputError(Exception):\n",
    "    \"\"\"Exception raised when there're errors in input\"\"\"\n",
    "    def __init__(self, value): # 自定义异常类型的初始化\n",
    "        self.value = value\n",
    "    def __str__(self): # 自定义异常类型的string表达形式\n",
    "        return (\"{} is invalid input\".format(repr(self.value)))\n",
    "    \n",
    "try:\n",
    "    raise MyInputError(1) # 抛出MyInputError这个异常\n",
    "except MyInputError as err:\n",
    "    print('error: {}'.format(err))\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 总结\n",
    "\n",
    "- 异常，通常是指程序运行的过程中遇到了错误，终止并退出。我们通常使用 try except 语句去处理异常，这样程序就不会被终止，仍能继续执行。\n",
    "- 处理异常时，如果有必须执行的语句，比如文件打开后必须关闭等等，则可以放在 finally  block 中。\n",
    "- 异常处理，通常用在你不确定某段代码能否成功执行，也无法轻易判断的情况下，比如数据库的连接、读取等等。正常的 flow-control 逻辑，不要使用异常处理，直接用条件语句解决就可以了。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
